package com.xiaoxi.exam.job;

import com.xiaoxi.exam.bean.OrderInfo;
import com.xiaoxi.exam.book.BrowserUtil;
import com.xiaoxi.exam.book.QuerySeatFinder;
import com.xiaoxi.exam.model.Account;
import com.xiaoxi.exam.service.AccountService;
import com.xiaoxi.exam.service.OrderService;
import com.xiaoxi.exam.utils.MailUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

@Slf4j
public class GetSeatOutJob implements Runnable {

  private static int pageSize = 10;
  private OrderService orderService;
  private AccountService accountService;
  private String url;
  private Map<String, String> sent = new HashMap<>();
  private FirefoxDriver driver;
  private String ocrUrl;

  public GetSeatOutJob(OrderService orderService,
      AccountService accountService, String url, FirefoxDriver driver, String ocrUrl) {
    this.orderService = orderService;
    this.accountService = accountService;
    this.url = url;
    this.driver = driver;
    this.ocrUrl = ocrUrl;
  }

  @SuppressWarnings("InfiniteLoopStatement")
  @Override
  public void run() {
    try {
      driver.get("https://toefl.neea.cn");
      WebDriverWait wait = new WebDriverWait(driver, 5);
      //noinspection unchecked
      wait.until(input -> driver.findElement(By.id("userName")));
      boolean login = BrowserUtil.login(driver, wait, "8348479", "2010shanghai-095X", 0, ocrUrl);
      if (login){
        BrowserUtil.clickConfirmBtn(driver, wait);
        while (true) {
          long total = orderService.totalEnablePreorders();
          int pageAt = 0;
          while (pageAt * pageSize < total) {

            List<OrderInfo> orderInfos = orderService.getPreorderLists(pageAt, pageSize)
                .parallelStream().distinct().collect(
                    Collectors.toList());
            orderInfos.forEach(o -> {
              if (Objects.isNull(sent.get(o.getId()))) {
                if (Objects.nonNull(o.getUId())) {
                  Account accountByUserId = accountService.getAccountByUserId(o.getUId());
                  log.info("account is : {}, userId is : {}", accountByUserId, o.getUId());

                  Map<String, String> result = QuerySeatFinder
                      .querySeat(driver, o.getExamCity(),
                          o.getExamSchool().stream().distinct().collect(
                              Collectors.toList()),
                          o.getExamTime().stream().distinct().collect(Collectors.toList()));
                  if (Objects.nonNull(result.get("school"))) {
                    MailUtil
                        .sendSSLMail(accountByUserId.getAccount(), accountByUserId.getPassword(),
                            o.getTel(), o.getExamCity(), result.get("school"), result.get("date"),
                            o.getId(), url);
                    sent.put(o.getId(), "1");
                  }
                }
              }
            });
            pageAt++;
          }
        }
      }
    } catch (Exception e) {
      log.error("meet error : {}", e.getMessage());
    }
  }

}
